package com.sx.micowell.module.smartDevice;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.example.mvvm.bar.TitleBar;
import com.example.mvvm.base.ContainerActivity;
import com.example.mvvm.base.action.TitleBarAction;
import com.example.mvvm.base.data.DataBindingConfig;
import com.example.mvvm.rx.RxBus;
import com.example.mvvm.rx.RxTimer;
import com.example.mvvm.until.LogUtils;
import com.example.mvvm.until.ToastUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnCancelListener;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.sx.micowell.R;

import com.sx.micowell.databinding.FragSearchDeviceBinding;
import com.sx.micowell.framework.app.AppConstant;
import com.sx.micowell.framework.app.MyFragment;
import com.sx.micowell.framework.arouth.RoutePath;
import com.sx.micowell.framework.model.smartDevice.SearchDeviceModel;
import com.sx.micowell.framework.tools.EventInfo;
import com.sx.micowell.module.smartDevice.adapter.BleDeviceListAdapter;
import com.tuya.sdk.eventbus.EventBus;
import com.tuya.smart.android.ble.api.LeScanSetting;
import com.tuya.smart.android.ble.api.ScanDeviceBean;
import com.tuya.smart.android.ble.api.ScanType;
import com.tuya.smart.home.sdk.TuyaHomeSdk;
import com.tuya.smart.home.sdk.bean.ConfigProductInfoBean;

import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


/**
 * @Author: YY
 * @Time: 2021/9/16
 * @Describe 搜索设备
 */
@Route(path = RoutePath.SMART_SEARCH_DEVICE)
public class SearchDeviceFragment extends MyFragment<FragSearchDeviceBinding, ContainerActivity>
        implements TitleBarAction {

    private SearchDeviceModel viewModel;

    private BleDeviceListAdapter bleDeviceListAdapter;

    @Override
    protected void initViewModel() {
        super.initViewModel();
        viewModel = getFragmentScopeViewModel(SearchDeviceModel.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.frag_search_device);
    }

    @Override
    protected void initView() {
        // 设置状态栏字体颜色
        ImmersionBar.with(this).statusBarDarkFont(true)
                .fitsSystemWindows(false).init();
        getBinding().title.setOnTitleBarListener(this);

        getBinding().tvNext.setOnClickListener(v -> getMyActivity().finish());
    }

    @Override
    protected void initData() {
        clickBlue();
    }

    @Override
    protected void initViewObservable() {
        super.initViewObservable();
        viewModel.loadingEvent.observe(this, aBoolean -> {
            if (aBoolean) {
                getBinding().cpiLoading.setVisibility(View.VISIBLE);
            } else {
                getBinding().cpiLoading.setVisibility(View.GONE);
            }
        });

        viewModel.matchStateEvent.observe(this, aBoolean -> {
            if (aBoolean) {
                getBinding().tvContent.setText("已成功配置1台设备");
                getBinding().tvNext.setVisibility(View.VISIBLE);
            }
            RxBus.getDefault().post(new EventInfo(AppConstant.EVENT_DEVICE_BIND_SUCCESS, null));
            hideDialog();
        });

        setBleDeviceList();
    }

    @Nullable
    @Override
    public TitleBar getTitleBar() {
        return getBinding().title;
    }

    @Override
    public void onLeftClick(View v) {
        getMyActivity().finish();
    }

    @SuppressLint("SetTextI18n")
    public void setBleDeviceList() {
        getBinding().recyclerDevs.setNestedScrollingEnabled(false);
        getBinding().recyclerDevs.setLayoutManager(new LinearLayoutManager(getContext()));

        viewModel.infoBeanListData.observe(this, infoBeanList -> {
            if (infoBeanList.size() > 0) {
                getBinding().tvTitle.setVisibility(View.GONE);
                getBinding().progress.setVisibility(View.VISIBLE);
                getBinding().tvContent.setVisibility(View.VISIBLE);
                getBinding().tvContent.setText("扫描到" + infoBeanList.size() + "个设备");
                if (bleDeviceListAdapter == null) {
                    bleDeviceListAdapter = new BleDeviceListAdapter(infoBeanList);
                    getBinding().recyclerDevs.setAdapter(bleDeviceListAdapter);

                    bleDeviceListAdapter.addChildClickViewIds(R.id.image_gray_right, R.id.toggle_agree);
                    bleDeviceListAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
                        @Override
                        public void onItemChildClick(@NonNull BaseQuickAdapter adapter,
                                                     @NonNull View view, int position) {
                            LogUtils.d("onItemClick " + position);
                            showDialog("正在配置");
                            viewModel.stopScan();
                            viewModel.startActivator(position);
                        }
                    });
                }
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        viewModel.stopScan();
    }

    @SuppressLint("CheckResult")
    public void clickBlue() {
        BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
        if (blueAdapter != null) {
            if (blueAdapter.isEnabled()) {
                LogUtils.d("蓝牙已经打开");
                viewModel.startScan();
            } else {
                if (turnOnBluetooth()) {
                    Observable.just("startScan").delay(5, TimeUnit.SECONDS)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(s -> {
                                viewModel.startScan();
                            });
                }
            }
        }
    }

    /**
     * 强制开启当前 Android 设备的 Bluetooth
     * @return true：强制打开 Bluetooth　成功　false：强制打开 Bluetooth 失败
     */
    public boolean turnOnBluetooth() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter
                .getDefaultAdapter();

        if (bluetoothAdapter != null) {
            return bluetoothAdapter.enable();
        }
        return false;
    }
}
